package com.wondertek.poms.sync.utils;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wondertek.poms.dao.po.SyncTask;
import com.wondertek.poms.sync.config.StartConfig;
import com.wondertek.poms.transform.xmlvo.SvcCont;
import com.wondertek.poms.transform.xmlvo.SyncRequest;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SourceUtil {
	
	@Autowired
	private StartConfig config;

    /**
     * 回执上游媒资系统统一方法
     * 使用场景：各个需要同步锁控制范围，mq接收后部分，无论对错，都需要回执上游程序
     *
     * @param syncRequest
     * @param isSuccess
     */
    public void pomsResponse(SyncRequest syncRequest, boolean isSuccess) {
        ContentResponse contentResponse = new ContentResponse(syncRequest);
        if (isSuccess) {
            contentResponse.setResult(ContentResponse.RESULT_SUCCESS);
        } else {
            contentResponse.setResult(ContentResponse.RESULT_FAILED);
        }
        sendNotifyRequest(syncRequest, contentResponse);
    }
    
    /**
     * 回执上游媒资系统
     *
     * @param syncRequest
     * @param isSuccess
     */
    public void pomsResponse(SyncTask st, boolean isSuccess) {
        ContentResponse contentResponse = new ContentResponse(st);
        if (isSuccess) {
            contentResponse.setResult(ContentResponse.RESULT_SUCCESS);
        } else {
            contentResponse.setResult(ContentResponse.RESULT_FAILED);
        }
        sendNotifyRequest(st, contentResponse);
    }
    
    /**
     * 内容回执http请求
     *
     * @param st
     * @return 发送异常为false，否则为true
     */
    public boolean sendNotifyRequest(SyncTask st, ContentResponse contentResponse) {
        boolean isSuc = true;
        String url = config.map.get(st.getAccessPlatformType());
        if (StrUtil.isBlank(url)) {
            log.error("sync cont " + st.getContentId() + " oprCode:" + st.getOprCode() + "platFormType:" + st.getAccessPlatformType() + " respUrl config is null, send resp reqeust canncelled");
            return isSuc;
        }
        
        try {
            log.info("sync cont " + st.getContentId() + " oprCode:" + st.getOprCode() + " sendNotifyRequest to " + url + " begin ...");
            String contentRsp = generateXml(contentResponse);
            log.info("sync cont " + st.getContentId() + " oprCode:" + st.getContentId() + " gen resp data :" + contentRsp);

            String response = "";
            int reTry = 3;
            for (int n = 0; n < reTry; n++) {
                try {
                    HttpResponse execute = HttpRequest.post(url).body(contentRsp, "UTF-8").timeout(60000).execute();

                    if (execute.getStatus() == 200) {
                        log.info("==sync cont [" + st.getContentId() + "] retry [" + n + "] times SUCCESS!==");
                        break;
                    }
                } catch (Exception e) {
                    log.info("==sync cont [" + st.getContentId() + "] retry [" + n + "] times ==");
                    e.printStackTrace();
                    if (n == 1) {
                        throw new Exception(e);
                    }
                }
            }

            log.info("sync cont " + st.getContentId() + " oprCode:" + st.getOprCode() + " sendNotifyRequest to " + url + " end,get response [" + response + "]");
            isSuc = true;

        } catch (Exception e) {
            log.error("sync cont " + st.getContentId() + " oprCode:" + st.getOprCode() + " sendNotifyRequest to " + url + " end,exception occur", e);
            isSuc = false;
        }
        return isSuc;
    }

    /**
     * 内容回执http请求
     *
     * @param st
     * @return 发送异常为false，否则为true
     */
    public boolean sendNotifyRequest(SyncRequest st, ContentResponse contentResponse) {
        boolean isSuc = true;
        SvcCont svcCont = st.getSvcCont();
        String url = config.map.get(st.getAccessPlatformType());
        if (StrUtil.isBlank(url)) {
            log.error("sync cont " + svcCont.getContentID() + " oprCode:" + svcCont.getOprCode() + "platFormType:" + st.getAccessPlatformType() + " respUrl config is null, send resp reqeust canncelled");
            return isSuc;
        }


        try {
            log.info("sync cont " + svcCont.getContentID() + " oprCode:" + svcCont.getOprCode() + " sendNotifyRequest to " + url + " begin ...");
            String contentRsp = generateXml(contentResponse);
            log.info("sync cont " + svcCont.getContentID() + " oprCode:" + svcCont.getOprCode() + " gen resp data :" + contentResponse);

            String response = "";
            int reTry = 3;
            for (int n = 0; n < reTry; n++) {
                try {
                    HttpResponse execute = HttpRequest.post(url).body(contentRsp, "UTF-8").timeout(60000).execute();

                    if (execute.getStatus() == 200) {
                        log.info("==sync cont [" + svcCont.getContentID() + "] retry [" + n + "] times SUCCESS!==");
                        break;
                    }
                } catch (Exception e) {
                    log.info("==sync cont [" + svcCont.getContentID() + "] retry [" + n + "] times ==");
                    e.printStackTrace();
                    if (n == 1) {
                        throw new Exception(e);
                    }
                }
            }

            log.info("sync cont " + svcCont.getContentID() + " oprCode:" + svcCont.getOprCode() + " sendNotifyRequest to " + url + " end,get response [" + response + "]");
            isSuc = true;

        } catch (Exception e) {
            log.error("sync cont " + svcCont.getContentID() + " oprCode:" + svcCont.getOprCode() + " sendNotifyRequest to " + url + " end,exception occur");
            log.error("", e);
            isSuc = false;
        }
        return isSuc;
    }

    /**
     * 对象转化为xml
     *
     * @param contentResponse
     * @return
     */
    private static String generateXml(ContentResponse contentResponse) {
        StringBuffer sbf = new StringBuffer();
        sbf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").append("<CMS>");
        sbf.append("<AccessID>").append(contentResponse.getAccessId()).append("</AccessID>");
        sbf.append("<AccessSEQ>").append(contentResponse.getAccessSeq()).append("</AccessSEQ>");
        sbf.append("<AccessPwd>").append(contentResponse.getAccessPwd()).append("</AccessPwd>");
        sbf.append("<AccessPlatformType>").append(contentResponse.getAccessPlatformType()).append("</AccessPlatformType>");
        sbf.append("<AccessPlatformID>").append(contentResponse.getAccessPlatformID()).append("</AccessPlatformID>");
        sbf.append("<Version>").append(contentResponse.getVersion()).append("</Version>");
        sbf.append("<SvcCont>");
        sbf.append("<ContentID>").append(contentResponse.getContentID()).append("</ContentID>");
        sbf.append("<CPID>").append(contentResponse.getCpID()).append("</CPID>");
        sbf.append("<OprCode>").append(contentResponse.getOprCode()).append("</OprCode>");
        sbf.append("<OprTime>").append(contentResponse.getOprTime()).append("</OprTime>");
        sbf.append("<Priority>").append(contentResponse.getPriority()).append("</Priority>");
        sbf.append("<ServType>").append(contentResponse.getServType()).append("</ServType>");
        sbf.append("<Result>").append(contentResponse.getResult()).append("</Result>");
        sbf.append("<Version>").append(contentResponse.getAccessId()).append("</Version>");

        List<String> items = contentResponse.getItems();
        if (contentResponse.getOprCode().equals("3") && items != null && items.size() > 0) {
            sbf.append("<Items>");
            items.forEach(v -> {
                sbf.append("<Item>").append(contentResponse.getAccessId()).append("</Item>");
            });
            sbf.append("</Items>");
        }
        sbf.append("</SvcCont></CMS>");
        return sbf.toString();
    }


}
